package com.xjtu.platform.security.forgetPwd;

import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.Result;
import com.xjtu.platform.security.register.SendMail;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/security/forgetPwd")
public class forgetPwdAPI {
    static Random r=new Random();
    static int sendcode;
    static int codestart;


    @Resource
    private ForgetPwdService forgetPwdService;

    @Resource
    private CommonService commonService;

    @PostMapping("/sendmail")
    public Result SendMail(@RequestBody ForgetPwdDto forgetPwdDto) {
        String mail = forgetPwdDto.getEmail();
        String user_id = forgetPwdDto.getUser_id();
        try {
            int code = sendemailcode(mail);
            boolean ok = forgetPwdService.insertFlag(forgetPwdDto,code);
            commonService.setCache(user_id,"");
            return Result.success("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_SYS,"发送失败");
        }
    }

    public static int sendemailcode(String targetmail){
        try {
            int code=r.nextInt(900000)+100000;
            codestart = (int) System.currentTimeMillis();
            SendMail.send(targetmail,"您的验证码为： \n"+ code+"\n"+"有效时间为10分钟");
            sendcode=code;
            return sendcode;

        } catch (Exception e) {
            e.printStackTrace();
            return 0;

        }

    }

    @PostMapping("")
    public Result updatePassword(@RequestBody ForgetPwdDto forgetPwdDto){
        String user_id = forgetPwdDto.getUser_id();
        int flag = forgetPwdService.getFlag(forgetPwdDto);
        long currentTime = System.currentTimeMillis();
        System.out.println(currentTime);
        long cachetime = forgetPwdService.getCachetime(user_id);
        if(currentTime - cachetime <= 600000) {
            if (flag == forgetPwdDto.getUserCode()) {
                boolean ok = forgetPwdService.updatePwd(forgetPwdDto);
                if (ok) {
                    return Result.success("修改密码成功!!!");
                } else {
                    return Result.fail(Result.ERR_CODE_SYS, "系统维护中.......");
                }
            } else {
                return Result.fail(Result.ERR_CODE_SYS, "验证码错误");
            }
        }else {
            return Result.fail(Result.ERR_CODE_SYS, "验证码时间超过10分钟");
        }
    }

    @PostMapping("/getEmail")
    public Result getEmail(@RequestBody ForgetPwdDto forgetPwdDto){
        Map<String,Object> page = forgetPwdService.getEmail(forgetPwdDto);
        return Result.success(page);
    }
}
